package main

import (
	"fmt"
	"log"
	"strings"
	"http"
	"io/ioutil"
	"github.com/hoisie/web.go"
	"github.com/hoisie/mustache.go"
)

const page_str = `
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <title>Get your weather on</title>
  <link rel="stylesheet" href="/css/master.css" type="text/css" media="screen" />
</head>
<body>
<div class="c">
<h1>Get your weather on</h1>
%s
</div>
</body>
</html>
`

const css_str = `
body { font-family:"DejaVu Sans Mono", "Bitstream Vera Sans Mono", monospace; text-transform:uppercase; }
a { color:#777; }
.c { width:400px; margin:0 auto; margin-top:50px; }
`

func page(city, content string) string {
	return fmt.Sprintf(page_str, content)
}

func url_to_buf(url string) []byte {
	if r, _, err := http.Get(url); err == nil {
		b, err := ioutil.ReadAll(r.Body)
		r.Body.Close()
		if err == nil {
			return b
		}
	}
	return make([]byte, 0)
}

func weather_for(location string) string {
	w, err := GetCachedWeather(strings.ToUpper(location))
	if err != nil {
		log.Printf("error getting Weather: %v\n", err)
		return ""
	}
	t := `
		<h2>{{Location}}</h2>
		{{Conditions}}, {{Temperature}} degrees<br/>
		Humidity {{Humidity}}<br/>
		Wind speed {{Wind}} MPH<br/>
		<br/>
		{{#Days}}
		<strong>{{#Date}}{{Weekday}}{{/Date}}</strong><br/>
		{{Conditions}}<br/>
		High of {{#High}}{{Fahrenheit}}{{/High}}, low of {{#Low}}{{Fahrenheit}}{{/Low}}<br/>
		<br/>
		{{/Days}}
	`
	m := map[string]interface{}{}
	m["Location"] = w.Display_location.Full
	m["Conditions"] = w.Weather
	m["Temperature"] = w.Temp_f
	m["Humidity"] = w.Relative_humidity
	m["Wind"] = w.Wind_mph
	m["Days"] = w.SimpleForecast.ForecastDay
	s := mustache.Render(t, m)
	return s
}

func get_path(ctx *web.Context, path string) {
	log.Printf("get_path: %s\n", path)
	t := page(path, fmt.Sprintf("%s", weather_for(path)))
	m := map[string]interface{}{}
	s := mustache.Render(t, m)
	ctx.WriteString(s)
}

func get_root(ctx *web.Context) {
	get_path(ctx, "TXL")
}

func get_css(ctx *web.Context, path string) {
	log.Printf("get_css\n")
	ctx.SetHeader("Content-Type", "text/css", false)
	ctx.WriteString(css_str)
}

func get_favicon(ctx *web.Context) {
	log.Printf("get_favicon\n")
	ctx.WriteString("")
}
